package com.chub.study.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @author : chub
 * @version : V1.0.0
 * @fileName : CustomDateJsonSerializer.java
 * @description : 日期反序列化工具,将时间字符串"yyyy-MM-dd"转换成LocalDateTime
 * @createTime : 2021-10-27 14:12
 */
public class JsonDateDeserializer extends JsonDeserializer<LocalDateTime> {
    /**
     * 将时间字符串"yyyy-MM-dd"不能直接转换成LocalDateTime, 先转成LocalDate，再转成LocalDateTime
     * @param dateStr
     * @param datePattern
     * @return
     */
    public LocalDateTime parseLocalDateTime(String dateStr, String datePattern){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(datePattern);
        LocalDate localDate = LocalDate.parse(dateStr, dateTimeFormatter);
        return localDate.atStartOfDay();
    }

    /**
     * 通过hutool工具将不同日期字符串转成LocalDateTime类型
     * @param dateStr
     * @return
     */
    public LocalDateTime parseLocalDateTime(String dateStr){
        LocalDateTime localDateTime = null;
        System.out.println("dateStr: " + dateStr);
        if (dateStr.matches("\\d{4}[-]\\d{1,2}[-]\\d{1,2}")) {
            localDateTime = DateUtil.parseLocalDateTime(dateStr, DatePattern.NORM_DATE_PATTERN);
        } else if (dateStr.matches("\\d{4}[-]\\d{1,2}[-]\\d{1,2}\\s+\\d{1,2}[:]\\d{1,2}")) {
            localDateTime = DateUtil.parseLocalDateTime(dateStr, DatePattern.NORM_DATETIME_MINUTE_PATTERN);
        } else if (dateStr.matches("\\d{4}[-]\\d{1,2}[-]\\d{1,2}\\s+\\d{1,2}[:]\\d{1,2}[:]\\d{1,2}")) {
            localDateTime = DateUtil.parseLocalDateTime(dateStr, DatePattern.NORM_DATETIME_PATTERN);
        } else if (dateStr.matches("\\d{4}[-]\\d{1,2}[-]\\d{1,2}\\s+\\d{1,2}[:]\\d{1,2}[:]\\d{1,2}[.]\\d{1,3}")) {
            localDateTime = DateUtil.parseLocalDateTime(dateStr, DatePattern.NORM_DATETIME_MS_PATTERN);
        } else if (dateStr.matches("\\d+")) {
//            localDateTime = DateUtil.parseLocalDateTime(dateStr, DatePattern.NORM_DATETIME_MS_PATTERN);
            localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(dateStr)), ZoneId.systemDefault());
        }

        return localDateTime;
    }

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateStr = p.getText();
        return parseLocalDateTime(dateStr);
//        return this.parseLocalDateTime(dateStr, DatePattern.NORM_DATE_PATTERN);
    }
}
